package com.cah.game;

import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.cah.library.DatabaseHelper;
import com.cah.library.UserFunctions;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class GameHistoryFragment extends Fragment
{
	private String gameKey, userKey;
	private int gameStatus, roundEnd;
	LinearLayout historyLayout, scoreLayout;
	MainActivity main;
	String oldBlackText;
	JSONObject historyInfo;
	SparseArray<String> cardIdTextMap;
	
	public GameHistoryFragment(String gameKey, int gameStatus, int roundEnd)
	{
		super();
		this.gameKey=gameKey;
		this.gameStatus=gameStatus;
		this.roundEnd=roundEnd;
	}
	
	public GameHistoryFragment()
	{
		super();
		this.gameKey = "";
		this.gameStatus = -1;
		this.roundEnd = -1;
	}
	
	public void onSaveInstanceState(Bundle outState)
	{
		outState.putString("gameKey", gameKey);
		outState.putInt("gameStatus", gameStatus);
		outState.putInt("roundEnd", roundEnd);
		outState.putString("historyInfo", historyInfo.toString());
	}
	
	public void onActivityCreated(Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
		
		main = (MainActivity)getActivity();
		main.actionBar.setDisplayHomeAsUpEnabled(true);
		main.setTitle(main.currentGameName);
		
		main.historyBackVisible = true;
		main.historyForwardVisible = true;
		
		if(roundEnd == -1)
		{
			main.historyForwardVisible = false;
		}
		else if(roundEnd < 10)
		{
			main.historyBackVisible = false;
		}
		
		main.invalidateOptionsMenu();
		
		historyLayout = (LinearLayout)main.findViewById(R.id.historyLayout);
		
		if(savedInstanceState != null)
		{
			gameKey = savedInstanceState.getString("gameKey");
			gameStatus = savedInstanceState.getInt("gameStatus");
			roundEnd = savedInstanceState.getInt("roundEnd");
			try
			{
				historyInfo = new JSONObject(savedInstanceState.getString("historyInfo"));
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
			setHistoryInfo();
		}
		else
		{
			new HistoryProcess().execute();
		}
	}
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		return inflater.inflate(R.layout.game_history, container, false);
	}

	private void setHistoryInfo()
	{
		try
		{
			JSONArray value = historyInfo.getJSONArray("value");
			SparseArray<JSONObject> sortedJsons = new SparseArray<JSONObject>();
			
			int lastRound = 0;
			
			for(int k=0;k<value.length();k++)
			{
				JSONObject round = value.getJSONObject(k);
				int roundId = round.getInt("roundNumber");
				sortedJsons.put(roundId, round);
				
				if(roundId > lastRound)
				{
					lastRound = roundId;
				}
			}
			
			roundEnd = lastRound;
			int stop = lastRound - 10;
			if(lastRound <= 10)
			{
				stop = 0;
			}
			
			for (int k=lastRound;k>stop;k--)
			{
				JSONObject round = sortedJsons.get(k);
				int roundId = k;
				int oldBlackId = round.getInt("blackCardId");
				JSONArray submissions = round.getJSONArray("submissions");
				String oldCzarHandle = round.getString("czar");
				String winner = round.getString("winner");
				LinearLayout roundLayout = new LinearLayout(main);
				LinearLayout horizontalLayout = new LinearLayout(main);
				LinearLayout submissionLayout = new LinearLayout(main);
				int padding = main.pxToDp(10);
				roundLayout.setPadding(0, padding, 0, 0);
				roundLayout.setOrientation(LinearLayout.VERTICAL);
				historyLayout.addView(roundLayout);
				
				horizontalLayout.setOrientation(LinearLayout.HORIZONTAL);
				submissionLayout.setOrientation(LinearLayout.VERTICAL);
				
				roundLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
				horizontalLayout.setBackground(getResources().getDrawable(R.drawable.back));
				
				GetBlackCardInfoProcess blackProcess = new GetBlackCardInfoProcess();
				blackProcess.execute((Integer)oldBlackId);
				oldBlackText = blackProcess.get()[1];
				
				TextView roundHeader = new TextView(main);
				roundHeader.setGravity(Gravity.CENTER_HORIZONTAL);
				padding = main.pxToDp(5);
				roundHeader.setPadding(padding, padding, padding, padding);
				String headerText = "Round " + roundId + ": " + oldCzarHandle + " picked.";
				roundLayout.addView(roundHeader);
				roundHeader.setTextColor(getResources().getColor(R.color.black));
				roundHeader.setBackground(getResources().getDrawable(R.drawable.grayback));
				roundHeader.setText(headerText);
				
				horizontalLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
				roundLayout.addView(horizontalLayout);
				TextView oldBlackTextView = new TextView(main);
				padding = main.pxToDp(2);
				oldBlackTextView.setPadding(padding, padding, padding, padding);
				oldBlackTextView.setText(oldBlackText);
				oldBlackTextView.setGravity(Gravity.CENTER_VERTICAL);
				oldBlackTextView.setTextColor(getResources().getColor(R.color.white));
				oldBlackTextView.setBackgroundColor(getResources().getColor(R.color.black));
				oldBlackTextView.setLayoutParams(new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 0.45f));
				horizontalLayout.addView(oldBlackTextView);
				
				submissionLayout.setLayoutParams(new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 0.55f));
				horizontalLayout.addView(submissionLayout);
				
				for(int i=0;i<submissions.length();i++)
				{
					JSONObject submission = submissions.getJSONObject(i);
					String playerName = submission.getString("username");
					
					
					JSONArray cards = submission.getJSONArray("submission");
					int[] cardIdArray = new int[cards.length()];
					
					for(int j=0;j<cards.length();j++)
					{
						cardIdArray[j] = cards.getInt(j);
					}
					
					GetWhiteCardTextProcess whiteProcess = new GetWhiteCardTextProcess();
					whiteProcess.execute(cardIdArray);
					
					cardIdTextMap = whiteProcess.get();
					
					String submissionText = playerName + " submitted: ";
					
					for(int j=0;j<cardIdArray.length;j++)
					{
						if(j>0)
						{
							submissionText += ", ";
						}
						
						submissionText += cardIdTextMap.get(cardIdArray[j]);
					}
					
					TextView submissionTextView = new TextView(main);
					padding = main.pxToDp(1);
					submissionTextView.setPadding(padding, padding, padding, padding);
					submissionTextView.setBackgroundColor(getResources().getColor(R.color.white));
					submissionTextView.setTextColor(getResources().getColor(R.color.gray));
					submissionTextView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
					if(playerName.equals(winner))
					{
						submissionTextView.setBackground(getResources().getDrawable(R.drawable.back));
						submissionTextView.setTextColor(getResources().getColor(R.color.black));
					}
					
					submissionTextView.setText(submissionText);
					
					submissionLayout.addView(submissionTextView);
				}
				
			}
			
		} catch (JSONException e)
		{
			e.printStackTrace();
		} catch (InterruptedException e)
		{
			e.printStackTrace();
		} catch (ExecutionException e)
		{
			e.printStackTrace();
		}
	}
	
	private class HistoryProcess extends AsyncTask<Void, Void, JSONObject>
	{
		ProgressDialog pdia;
		@Override
		protected void onPreExecute()
		{
			pdia = new ProgressDialog(main);
			pdia.setMessage("Loading game history...");
			pdia.show();
		}
		
		@Override
		protected JSONObject doInBackground(Void... params)
		{
			UserFunctions uf = new UserFunctions(userKey);
			return uf.fetchHistoryPage(gameKey, roundEnd);
		}
		
		protected void onPostExecute(JSONObject json)
		{
			try
			{
				if(json.getInt("success")==1)
				{
					historyInfo = json;
					setHistoryInfo();
				}
				else
				{
					Toast.makeText(main, "Something went wrong!", Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
			
			pdia.dismiss();
		}
		
	}
	
	protected class GetWhiteCardTextProcess extends AsyncTask<int[], Void, SparseArray<String>>
	{

		@Override
		protected SparseArray<String> doInBackground(int[]... params)
		{
			SparseArray<String> map = new SparseArray<String>();
			int[] ids = params[0];
			DatabaseHelper mydbhelper = new DatabaseHelper(main);
			Cursor c = mydbhelper.getWhiteTexts(ids);
			try{
				while(c.moveToNext())
				{
					map.put(c.getInt(c.getColumnIndex("_id")), c.getString(c.getColumnIndex("text")));
				}
			}
			finally{
				c.close();
				mydbhelper.close();
			}
			
			return map;
		}
	}
	
	//Returns {_id, text, pick}
	protected class GetBlackCardInfoProcess extends AsyncTask<Integer, Void, String[]>
	{

		@Override
		protected String[] doInBackground(Integer... params)
		{
			int id = params[0].intValue();
			DatabaseHelper mydbhelper = new DatabaseHelper(main);
			Cursor c = mydbhelper.getBlackCard(id);
			c.moveToFirst();
			String[] result = new String[3];
			result[0] = c.getString(c.getColumnIndex("_id"));
			result[1] = c.getString(c.getColumnIndex("text"));
			result[2] = c.getString(c.getColumnIndex("pick"));
			return result;
		}
		
	}
	
	public int getRoundEnd()
	{
		return roundEnd;
	}
	
	public int getGameStatus()
	{
		return gameStatus;
	}
	
	public String getGameKey()
	{
		return gameKey;
	}
}
